package com.example.nettydemo.网络编程.TCP;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class 服务端 {


//    public 服务端(int port){
//    }//创建服务器ServerSocket对象，指明自己和端口号

    public static void main(String[] args) {
        ServerSocket ss = null;
        Socket socket = null;

        InputStream ips = null;
        OutputStream ops = null;
        ByteArrayOutputStream baos = null;
        try {
            //创建服务器ServerSocket对象，指明自己和端口号
            ss = new ServerSocket(65534);

            while (true) {
                socket = ss.accept();//接受客户端的Socket
                System.out.println(socket.getInetAddress().getHostAddress()+"连接了服务器");
                ips = socket.getInputStream();//获取字节输入流
                baos = new ByteArrayOutputStream();//防止汉字乱码
                byte[] bytes = new byte[5];
                int len;
                while ((len = ips.read(bytes)) != -1) {
                    baos.write(bytes, 0, len);//把输入流的内容  写道ByteArrayOutputStream里
                }
                System.out.println(socket.getInetAddress() + ":" + baos.toString());
                ops = socket.getOutputStream();
                ops.write("我收到了 你好".getBytes());
                socket.shutdownOutput();

            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                ops.close();
                baos.close();
                ips.close();
                socket.close();
                ss.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }
}